package com.bawei.module_mall.adapter

import android.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_mall.model.Item
import com.bawei.module_mall.R
import com.bawei.module_mall.http.repository.ShopRepository
import com.bawei.module_mall.model.DeleteModel
import com.bumptech.glide.Glide
import android.widget.Button

class ShopAdapter(
    private val items: MutableList<Item>,
    private val onCountChange: (Item, String) -> Unit, // action: "plus", "minus", "delete_confirm"
    private val onCheckedChange: (Item, Boolean) -> Unit,
    private val onCollectClick: ((Item) -> Unit)? = null // 新增收藏点击回调
) : RecyclerView.Adapter<ShopAdapter.ShopViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShopViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cart_product, parent, false)
        return ShopViewHolder(view)
    }

    override fun onBindViewHolder(holder: ShopViewHolder, position: Int) {
        holder.bind(items[position])
    }

    override fun getItemCount(): Int = items.size

    inner class ShopViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val checkbox: CheckBox = itemView.findViewById(R.id.checkbox_select)
        private val image: ImageView = itemView.findViewById(R.id.iv_product_img)
        private val name: TextView = itemView.findViewById(R.id.tv_product_name)
        private val attr: TextView = itemView.findViewById(R.id.tv_product_attr)
        private val price: TextView = itemView.findViewById(R.id.tv_product_price)
        private val count: TextView = itemView.findViewById(R.id.tv_count)
        private val btnMinus: ImageButton = itemView.findViewById(R.id.btn_minus)
        private val btnPlus: ImageButton = itemView.findViewById(R.id.btn_plus)
        private val btnDelete: Button = itemView.findViewById(R.id.btn_delete)
        private val btnCollect: Button = itemView.findViewById(R.id.btn_collect)
        private val contentLayout: View = itemView.findViewById(R.id.layout_content)
        private val swipeButtons: View = itemView.findViewById(R.id.layout_swipe_buttons)

        private var isOpen = false
        private var startX = 0f
        private var lastX = 0f
        private var translationLimit = 140f // 按钮总宽度（将动态赋值）

        init {
            // 动态获取按钮区宽度，保证滑动距离刚好露出全部按钮
            itemView.post {
                translationLimit = swipeButtons.width.toFloat()
            }
            // 优化滑动体验：实时跟随手指滑动，松手自动展开/收回
            contentLayout.setOnTouchListener { v, event ->
                when (event.action) {
                    android.view.MotionEvent.ACTION_DOWN -> {
                        startX = event.rawX
                        lastX = startX
                        false
                    }
                    android.view.MotionEvent.ACTION_MOVE -> {
                        val dx = event.rawX - startX
                        val moveX = event.rawX - lastX
                        lastX = event.rawX
                        // 允许更轻松滑动，阈值调小
                        val newTrans = (contentLayout.translationX + moveX).coerceIn(-translationLimit, 0f)
                        contentLayout.translationX = newTrans
                        // 如果滑动距离超过-10就展开
                        if (dx < -10) {
                            isOpen = true
                        } else if (dx > 10) {
                            isOpen = false
                        }
                        true
                    }
                    android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
                        // 松手后自动判断展开/收回
                        if (contentLayout.translationX < -translationLimit / 2) {
                            contentLayout.animate().translationX(-translationLimit).setDuration(120).start()
                            isOpen = true
                        } else {
                            contentLayout.animate().translationX(0f).setDuration(120).start()
                            isOpen = false
                        }
                        true
                    }
                    else -> false
                }
            }
            // 点击内容关闭侧滑
            contentLayout.setOnClickListener {
                if (isOpen) {
                    contentLayout.animate().translationX(0f).setDuration(100).start()
                    isOpen = false
                }
            }
            // 删除按钮
            btnDelete.setOnClickListener {
                val dialog = AlertDialog.Builder(itemView.context)
                    .setTitle("确认删除")
                    .setMessage("是否删除该商品？")
                    .setPositiveButton("确定") { _, _ ->
                        onCountChange(items[adapterPosition], "delete_confirm")
                        contentLayout.animate().translationX(0f).setDuration(100).start()
                        isOpen = false
                    }
                    .setNegativeButton("取消") { _, _ ->
                        contentLayout.animate().translationX(0f).setDuration(100).start()
                        isOpen = false
                    }
                dialog.show()
            }
            // 收藏按钮
            btnCollect.setOnClickListener {
                onCollectClick?.invoke(items[adapterPosition])
            }
        }

        fun bind(item: Item) {
            // 商品图片
            Glide.with(itemView).load(item.mainImageUrl).into(image)
            // 商品名称
            name.text = item.goodsName
            // 商品属性
            attr.text = item.goodsSkuName
            // 商品价格
            price.text = "¥${item.price}"
            // 数量
            count.text = item.number.toString()
            // 选择框（与item.isChecked同步，避免复用问题）
            checkbox.setOnCheckedChangeListener(null)
            checkbox.isChecked = item.isChecked
            checkbox.setOnCheckedChangeListener { _, isChecked ->
                onCheckedChange(item, isChecked)
            }
            btnMinus.setOnClickListener {
                if (item.number == 1) {
                    val dialog = AlertDialog.Builder(itemView.context)
                        .setTitle("确认删除")
                        .setMessage("是否删除该商品？")
                        .setPositiveButton("确定") { _, _ ->
                            onCountChange(item, "delete_confirm")
                        }
                        .setNegativeButton("取消", null)
                    dialog.show()
                }else{
                    onCountChange(item, "minus")
                }
            }
            btnPlus.setOnClickListener {
                onCountChange(item, "plus")
            }
        }
    }

    fun updateItem(newItem: Item) {
        val index = items.indexOfFirst { it.id == newItem.id }
        if (index != -1) {
            items[index] = newItem
            notifyItemChanged(index)
        }
    }

    fun setData(newList: List<Item>) {
        items.clear()
        items.addAll(newList)
        notifyDataSetChanged()
    }

    // 新增：全选/全不选
    fun setAllChecked(checked: Boolean) {
        items.forEach { it.isChecked = checked }
        notifyDataSetChanged()
    }
    // 新增：是否全选
    fun getAllChecked(): Boolean = items.all { it.isChecked }
    // 新增：获取所有选中商品
    fun getSelectedItems(): List<Item> = items.filter { it.isChecked }
    // 新增：获取全部商品
    fun getItems(): List<Item> = items
}